# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime

from absl import app

from coin.base.datetime_util import to_datetime
from coin.feed.fastfeed.native_wrapper import run_from_feed_cache
from coin.proto import coin_order_pb2
from coin.strategy.marketsim.core import spec_pb2, marketsim


class Strategy:
  def __init__(self, og, products):
    self._og = og
    self._products = products
    self._last_order_ts = 0
    self._og.add_execution_callback(self.on_execution)

  def on_book(self, book):
    if book.timestamp - self._last_order_ts < 2 * 10**9:
      return

    # print(to_datetime(book.timestamp), len(self._og.get_orders()))
    # for pos in self._og.get_positions():
    #  print(pos)

    for order in self._og.get_orders():
      if not order.cancel_submitted:
        self._og.cancel(order_id=order.order_id)

    self._og.submit(product=self._products[0],
                    side=coin_order_pb2.SELL_ORDER,
                    price=book.ask0().price,
                    qty=100.,
                    post_only=True)

    self._og.submit(product=self._products[0],
                    side=coin_order_pb2.BUY_ORDER,
                    price=book.bid0().price,
                    qty=100.,
                    post_only=True)

    self._last_order_ts = book.timestamp

  def on_execution(self, execution):
    pass

  def on_book_reset(self, sub_req, book_builder):
    book_builder.subscribe_book(self._products, self.on_book)


def main(args):
  from coin.exchange.bitmex.kr_rest.futures_product import BitmexFuturesProduct
  p = BitmexFuturesProduct.FromStr('BTC-USD.PERPETUAL')
  pspec = spec_pb2.ProductSpecProto(symbol=str(p),
                                    settlement_currency='BTC',
                                    inverse=True,
                                    maker_fee=-0.00025,
                                    taker_fee=0.00075,
                                    support_post_only=True,
                                    fastfeed_machine='feed-01.ap-northeast-1.aws',
                                    fastfeed_sub_req='Futures.Bitmex')

  msim = marketsim.MarketSim(default_machine='feed-01.ap-northeast-1.aws')
  msim.add_product(p, pspec)
  strategy = Strategy(msim, [p])

  run_from_feed_cache(msim.get_feed_sub_reqs(), [msim.on_book_reset, strategy.on_book_reset],
                      datetime.date(2019, 4, 1),
                      datetime.date(2019, 4, 2),
                      machine=msim.default_machine)

  print(msim.generate_sim_stat())


if __name__ == '__main__':
  app.run(main)
